package com.hs.dynamic.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.hs.dynamic.entity.UserDriver;
import com.hs.dynamic.req.UserReq;
import com.hs.dynamic.entity.R;
import com.hs.dynamic.entity.User;
import com.hs.dynamic.service.UserDriverService;
import com.hs.dynamic.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author 胡尚
 * @Date: 2024/8/2 10:12
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public R addUser(@RequestBody UserReq req) {
        userService.addUser(req);
        return R.ok();
    }

    @GetMapping
    public R queryUser() {

        List<User> userList = new ArrayList<>();
        userList.addAll(userService.findAll());
        return R.ok(userList);

    }

    @GetMapping("/sesstionTest")
    public R sesstionTest(@RequestParam(value = "dsKey",defaultValue = "hsWrite") String dsKey, HttpServletRequest request) {

        // 注意，这里存入session的key要和Service方法中@DS注解中的值对应上。而value要和配置文件中定义的数据源对应
        request.getSession().setAttribute("hs_session_db_key", dsKey);

        List<User> userList = new ArrayList<>();
        userList.addAll(userService.sessionFindAll());
        return R.ok(userList);

    }

    @Autowired
    private UserDriverService userDriverService;

    @Resource
    DynamicRoutingDataSource dataSource;

    @GetMapping("/dynamicAddTest")
    public R dynamicAddTest(@RequestParam(value = "userId") Long userId, HttpServletRequest request) {

        // 根据userId查询到该用户对应的数据源
        UserDriver userDriver = userDriverService.getByUserId(userId);
        // 创建一个数据源
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(userDriver.getDriverClassName());
        druidDataSource.setUrl(userDriver.getUrl());
        druidDataSource.setUsername(userDriver.getUsername());
        druidDataSource.setPassword(userDriver.getPassword());
        // 把新创建的数据源添加进DynamicRoutingDataSource中，这里的key就是该数据源的名字
        dataSource.addDataSource("hsNewDataSource", druidDataSource);


        // 注意，这里存入session的key要和Service方法中@DS注解中的值对应上。而value就是数据源的名字
        request.getSession().setAttribute("hs_session_db_key", "hsNewDataSource");

        List<User> userList = new ArrayList<>();
        userList.addAll(userService.sessionFindAll());
        return R.ok(userList);

    }

}
